<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { ElMessage, FormInstance, UploadFile } from 'element-plus'
  import { orderAnnexUpload } from '@/api/upload'
  import { saveRemark } from '@/api/order'
  import { OrderAPIRequestParam } from '@/typings/api/order'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    workIds: {
      type: Array<string>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'updated'): void
  }>()

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, formValidateResult, resetFormValidateResult } =
    useFormValidateService(['note'])

  // 表单验证规则
  const rules = ref({
    note: [
      {
        required: true,
        message: '请输入备注',
        trigger: ['blur', 'change'],
      },
    ],
    visitTypes: [
      {
        required: true,
        message: '请选择可见类型',
        trigger: ['blur', 'change'],
      },
    ],
  })

  // 弹窗状态
  const visible = ref(false)

  /**
   * 关闭事件
   */
  const onClose = () => {
    form.value = {
      note: '',
      fileList: [],
      visitTypes: [0],
    }
    visible.value = false
    resetFormValidateResult()
    emits('update:modelValue', visible.value)
  }

  // 表单
  const form = ref<{ note: string; fileList: Array<UploadFile>; visitTypes }>({
    note: '',
    fileList: [],
    visitTypes: [0],
  })

  /**
   * 移除图片事件
   * @param {object} file - 文件
   */
  // const handleRemove = (file: UploadFile) => {
  //   const index = form.value.fileList.findIndex((item) => item.url === file.url)
  //   form.value.fileList.splice(index, 1)
  // }

  /**
   * 文件上传
   * @param {object} file - 文件
   */
  // const handleChange = (file: UploadFile) => {
  //   const fileReader = new FileReader()
  //   fileReader.readAsDataURL(file.raw)
  //   fileReader.onload = () => {
  //     if (form.value.fileList.length + 1 > 5) {
  //       ElMessage({
  //         type: 'error',
  //         message: '最多只能上传5张图片',
  //       })
  //       return false
  //     }
  //     form.value.fileList.push(Object.assign(file, { url: fileReader.result }))
  //   }
  // }

  // form组件实例
  const formRef = ref<FormInstance | null>(null)

  // 保存加载
  const saveLoading = ref(false)

  /**
   * 确定事件
   */
  const onConfirm = () => {
    if (formRef.value) {
      formRef.value.validate(async (valid) => {
        if (valid) {
          saveLoading.value = true
          const data: OrderAPIRequestParam.SaveOrderRemark = {
            annexs: [],
            remark: '',
            workIds: [],
            visitTypes: [0],
          }

          data.remark = form.value.note
          data.workIds = props.workIds
          data.visitTypes = form.value.visitTypes

          for (let i = 0; i < form.value.fileList.length; i++) {
            const res = await orderAnnexUpload([form.value.fileList[i].raw])
            data.annexs.push(res.data.data.rows[0])
          }

          const saveResult = await saveRemark(data)
          ElMessage({
            type: saveResult.data.success ? 'success' : 'error',
            message: saveResult.data.message,
          })
          if (saveResult.data.success) {
            visible.value = false
            emits('update:modelValue', visible.value)

            form.value = {
              note: '',
              fileList: [],
              visitTypes: [0],
            }
            emits('updated')
          }
          saveLoading.value = false
        }
      })
    }
  }

  watch(
    () => props.modelValue,
    (value) => {
      visible.value = value
    },
  )
</script>

<template>
  <div>
    <HModal v-model="visible" @close="onClose" title="填写备注" width="auto">
      <div class="title">
        <span>当前选中</span>
        <span class="num">{{ props.workIds.length }}</span>
        <span>个工单进行批量备注！</span>
      </div>
      <el-form
        v-loading="saveLoading"
        ref="formRef"
        label-width="70"
        :rules="rules"
        :model="form"
        @validate="handleFormValidate"
        class="modal_form_content"
      >
        <!--工单备注-->
        <el-form-item
          label="工单备注"
          prop="note"
          class="form_textarea_item"
          :class="{ error_form_item: !formValidateResult['note'] }"
        >
          <el-input
            type="textarea"
            placeholder="请填写备注"
            v-model="form.note"
            maxlength="200"
            show-word-limit
            resize="both"
          />
        </el-form-item>

        <!--可见类型-->
        <el-form-item prop="visitTypes" class="form_checkbox_group_item" label="可见类型">
          <el-checkbox-group v-model="form.visitTypes" class="visit_type">
            <el-checkbox :value="0">
              <span class="visit_type_text">公开</span>
            </el-checkbox>
            <el-checkbox :value="1">
              <span class="visit_type_text">服务商可见</span>
            </el-checkbox>
            <el-checkbox :value="2">
              <span class="visit_type_text">工程师可见</span>
            </el-checkbox>
            <el-checkbox :value="3">
              <span class="visit_type_text">客户可见</span>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footerRight>
        <HButton is-modal type="primary" :loading="saveLoading" @click="onConfirm">确定</HButton>
        <HButton is-modal :loading="saveLoading" @click="onClose">关闭</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './ServiceProcess.scss';
</style>
